<?php

namespace App\Api\Controllers\LeshuaUnion;


use App\Exceptions\BizException;
use Illuminate\Support\Facades\Log;

class BaseController
{
    const Key = "88888888";

    static $instance;

    const MAIN_URL_Test = 'https://t-paygate.lepass.cn';
    const MAIN_URL_Pro = 'https://paygate.leshuazf.com';
    const QR_SUBMIT = '/cgi-bin/lepos_pay_gateway.cgi';

    const SCAN_PAY = '/cgi-bin/lepos_pay_gateway.cgi';

    const QUERY_ORDER = '/cgi-bin/lepos_pay_gateway.cgi';

    const REFUND = '/cgi-bin/lepos_pay_gateway.cgi';
    const REFUND_QUERY = '/cgi-bin/lepos_pay_gateway.cgi';

    const EmbedPay = '/saas-open-gateway/preorder-server/saas/plugin/preorder/create';

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function params(array $config, array $data): array
    {
        $params = [
            "agentId" => $config["orgId"],
            "currentAgentId" => $config["orgId"],
            "version" => "1.0",
            "reqSerialNo" => date("YmdHis", time()) . rand(100, 999) . rand(10000, 99999),
            "algorithm" => false,
            "data" => json_encode($data, JSON_UNESCAPED_UNICODE)
        ];
        $params["sign"] = $this->createSign($params, $config["key"]);
        return $params;
    }

    /**
     * ASCII排序
     * @param array $params
     * @param $key
     * @return bool|string
     */
    public function createSign(array $params, string $key = ""): string
    {
        if (empty($params)) {
            throw new BizException("参数不能为空");
        }
        ksort($params);
        $str = '';
        foreach ($params as $k => $val) {
            if (!is_array($val)) {
                $val = trim($val);
            }
            if ($val === '' || $val === null) {
                continue;
            }
            $str .= $k . '=' . $val . '&';
        }
        $str = $str . "key=" . $key;//注：key为商户密钥key
        $stringSignTemp = strtoupper(md5($str));
        Log::channel("leshuaunion")->info("createSign", [
            "str" => $str,
            "sign" => $stringSignTemp
        ]);
        return $stringSignTemp;
    }


    public function verifySign(array $params, string $key = "", bool $filterNull = true): string
    {
        if (empty($params)) {
            throw new BizException("参数不能为空");
        }
        ksort($params);
        $str = '';
        foreach ($params as $k => $val) {
            if (!is_array($val)) {
                $val = trim($val);
            }
            if ($filterNull) {
                if (empty($val) || $val === '' || $val === null) {
                    continue;
                }
            } else {
                if (is_array($val) && empty($val)) {
                    $val = "";
                }
            }
            $str .= $k . '=' . $val . '&';
        }
        $stringSignTemp = $str . "key=" . $key;//注：key为商户密钥key
        return md5($stringSignTemp);
    }

    public function verify($data, $key, bool $filterNull = true): bool
    {
        $sign = $data['sign'];
        unset($data["sign"]);
        $sign1 = $this->verifySign($data, $key, $filterNull);
        if ($sign == $sign1) {
            return true;
        }
        return false;
    }

    public function buildwww(string $url, array $data, $fun): array
    {
        $ch = curl_init();
//        $domain = self::MAIN_URL_Test;
//        if (env("APP_ENV") == "pro") {
        $domain = "https://saas-mch.leshuazf.com";
//        }
        curl_setopt($ch, CURLOPT_URL, $domain . $url); //设置选项，包括URL
        $headers = [
            "Content-Type" => "application/x-www-form-urlencoded",
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);

//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (is_array($data)) {
            $postData = http_build_query($data);
        } else {
            $postData = $data;
        }

        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        $output = curl_exec($ch); //执行并获取HTML文档内容
        curl_close($ch); //释放curl句柄
        $outputArr = $this->xml_to_array($output);
//        $output = json_decode($output, true);
        Log::channel("leshuaunion")->info($fun, [
            "url" => $domain . $url,
            "req" => $data,
            "res" => $outputArr
        ]);
        if (empty($outputArr) || !is_array($outputArr)) {
            throw new BizException("请求失败");
        }
        return $outputArr;
    }

    public function build(string $url, array $data, $fun): array
    {
        $ch = curl_init();
//        $domain = self::MAIN_URL_Test;
//        if (env("APP_ENV") == "pro") {
        $domain = self::MAIN_URL_Pro;
//        }
        curl_setopt($ch, CURLOPT_URL, $domain . $url); //设置选项，包括URL
        $headers = [
            "Content-Type" => "application/json",
            "charset" => "utf8"
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);

//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch); //执行并获取HTML文档内容
        curl_close($ch); //释放curl句柄
        $outputArr = $this->xml_to_array($output);
//        $output = json_decode($output, true);
        Log::channel("leshuaunion")->info($fun, [
            "url" => $domain . $url,
            "req" => $data,
            "res" => $outputArr
        ]);
        if (empty($outputArr) || !is_array($outputArr)) {
            throw new BizException("请求失败");
        }
        return $outputArr;

    }


    public function xml_to_array($xml)
    {
        if (!$xml) {
            die("xml数据异常！");
        }

        libxml_disable_entity_loader(true); //禁止引用外部xml实体
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $values;
    }


    protected function checkEmpty($value)
    {
        if (!isset($value)) {
            return true;
        }
        if ($value === null) {
            return true;
        }
        if (trim($value) === "") {
            return true;
        }
        return false;
    }

    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                // $v = $this->characet($v, $this->postCharset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        return $stringToBeSigned;
    }

}